<?php
namespace app\common\model;


use think\facade\Db;
use think\model\concern\SoftDelete;

class GoodsAttrsModel extends BaseModel
{
    use SoftDelete;

    protected $table='goods_attrs';

//    public function getTagsAttr($value)
//    {
////        $data = [];
////        $values = empty($value) ? [] : explode(",",$value) ;
////        foreach ($values as $item){
////            if(empty($item)) continue;
////            $data[] = intval($item);
////        }
//        return empty($value)?'': mb_substr($value,1,-1);
//    }

    public static function goodsStyleLists()
    {
        $where = [];
        $where[] = ['status','=',1];
        $where[] = ['is_style','=',1];
        $list = [];
        $attr_ids = [];
        self::where($where)->select()->each(function($item)use(&$list,&$attr_ids){
            $attr_ids[] = $item['id'];
            array_push($list,[
                'id'=>$item['id'],
                'name'=>$item['name'],
                'count'=>0,
            ]);
        });

        if(!empty($list)){
            $regexp_str_arr = [];
            foreach ($attr_ids as $id){
                $regexp_str_arr[] = ",$id,";
            }
            $all_regexp_str = implode('|',$regexp_str_arr);
            $where = [];
            $where[] = ['status','=',1];
            $where[] = ['tags','REGEXP',$all_regexp_str];
//            dump($where);exit;
            $all_tags = GoodsModel::where($where)->column('tags');
//            dump($all_tags);exit;
            $all_tags_arr = explode(',',implode(',',$all_tags));
            $tags_count = array_count_values($all_tags_arr);
            foreach ($list as &$vo){
                $tags_key = $vo['id'].'';
                $vo['count'] = isset($tags_count[$tags_key]) ? $tags_count[$tags_key] : 0;
            }
        }

        return $list;
    }


    public static function getSelectList(array $input_data=[])
    {
        $list = [];
        $where =[];
        $where[] = ['pid','=',0];
        if(isset($input_data['status'])){
            $where[] = ['status','=', $input_data['status']];
        }
        $level = $input_data['level']??1;
        if($level==2){
            $where_link_fun = function($query)use($input_data){
                if(isset($input_data['status'])){
                    $query->with(['linkChild'=>function($query)use($input_data){
                        $query->where(['status'=>$input_data['status']]);
                    }])->where(['status'=>$input_data['status']]);
                }else{
                    $query->with(['linkChild']);
                }
            };
        }else{
            $where_link_fun = function($query)use($input_data){
                if(isset($input_data['status'])){
                    $query->where(['status'=>$input_data['status']]);
                }
            };
        }


        self::with(['linkChild'=>$where_link_fun])->where($where)->order('sort','asc')->select()->each(function($item) use(&$list){
            $info = $item->apiNormalInfo();
            $linkChild = $item->getRelation('linkChild');
            $info['list'] = [];
            foreach ($linkChild as $child){
                $childInfo = $child->apiNormalInfo();
                $childInfo['list'] = [];
                $linkChildChild = $child->getRelation('linkChild');
                if(!empty($linkChildChild)){
                    foreach ($linkChildChild as $childchild){
                        $childInfo['list'][] = $childchild->apiNormalInfo();
                    }
                }

                $info['list'][] = $childInfo;
            }
            array_push($list,$info);
        });
        return $list;
    }



    public static function handleSaveData(array $input_data = [])
    {

        if( empty($input_data['name'])) throw new \Exception('请输入名字');

        !empty($input_data['name']) && $input_data['name'] = trim($input_data['name']);
//        $input_data['tags'] = !empty($input_data['tags']) ? ','.$input_data['tags'].',' : null;
        //验证名字是否存在
        $check_where = [];
        if(!empty($input_data['id'])){
            $check_where[] = ['id','<>',$input_data['id']];
        }
        $check_where[] = ['name','=',$input_data['name']];
        $model = self::where($check_where)->find();
        if(!empty($model)) throw new \Exception('标签已存在,请重新输入');
        //直接保存信息
        $model = (new self())->actionAdd($input_data);

    }

//    public static function handleSaveData(array $input_data = [])
//    {
//
//        $tags = empty($input_data['tags']) ? [] : array_values(array_filter(explode("\n",$input_data['tags'])));
//        if(empty($tags) && empty($input_data['name'])) throw new \Exception('请输入名字');
//
//        !empty($input_data['name']) && $input_data['name'] = trim($input_data['name']);
//
//        if(count($tags)>0){
//            $all_tags_names = [];
//            foreach ($tags as $item){
//                $all_tags_names[] =trim($item);
//            }
//            //查询已存在的标签
//            $exist_tags_name = self::whereIn('name',$all_tags_names)->column('name');
//
//            $insertAll = [];
//            foreach ($all_tags_names as $vo){
//                if (in_array($vo,$exist_tags_name)) continue;
//                $insertAll[] = [
//                    'name'=>$vo,
//                    'status'=>empty($input_data['status'])?1:$input_data['status'],
//                    'sort'=>empty($input_data['sort'])?100:$input_data['sort'],
//                    'create_time'=>time(),
//                    'update_time'=>time(),
//                ];
//            }
//            self::insertAll($insertAll);
//        }else{
//            //验证名字是否存在
//            $check_where = [];
//            if(!empty($input_data['id'])){
//                $check_where[] = ['id','<>',$input_data['id']];
//            }
//            $check_where[] = ['name','=',$input_data['name']];
//            $model = self::where($check_where)->find();
//            if(!empty($model)) throw new \Exception('标签已存在,请重新输入');
//            //直接保存信息
//            $model = (new self())->actionAdd($input_data);
//        }
//
//    }



    /**
     * 获取数据
     * @param array $input_data 请求内容
     * @param int|null $limit 页面条数
     * @throws
     * @return \think\Paginator
     * */
    public static function getAllCate(array $input_data=[])
    {
        $limit = $input_data['limit']??null;

        $where = [];
        $where[] = ['pid','=',0];
        if(isset($input_data['status'])){
            $where[]=['status','=',$input_data['status']];
        }
        if(isset($input_data['id'])){
            $where[]=['id','=',$input_data['id']];
        }

        !empty($input_data['keyword']) && $where[]=['name','like',"%".$input_data['keyword']."%"];

        $where_link_fun = function($query)use($input_data){
            if(isset($input_data['status'])){
                $query->with(['linkChild'=>function($query)use($input_data){
                    $query->where(['status'=>$input_data['status']]);
                }])->where(['status'=>$input_data['status']]);
            }else{
                $query->with(['linkChild']);
            }
        };



        return self::with(['linkChild'=>$where_link_fun])->where($where)->order('sort','asc')->paginate($limit);
    }



    public function apiNormalInfo()
    {

        return [
            'id'=>$this['id'],
            'name'=> (string)$this['name'],
            'url'=> (string)$this['url'],
        ];
    }

    public function linkChild()
    {
        return $this->hasMany(self::class,'pid')->order('sort asc');
    }

}